package org.kotboot.service

import org.kotboot.dao.AddressDao
import org.kotboot.domain.Address
import org.kotboot.enums.BoolState
import org.kotboot.kit.isNull
import org.kotboot.module.R
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import javax.annotation.Resource


@Service
open class AddressServ(

        @Resource val addressDao: AddressDao

) {

    val LOG:Logger = LoggerFactory.getLogger(AddressServ::class.java)


    fun findByConditionActive(map:MutableMap<String,Any?>):MutableList<Address>{
        map["del"] = BoolState.NO
        return addressDao.findByCondition(map)
    }

    fun findByCondition(map:MutableMap<String,Any?>):Address?{
        val findByCondition = addressDao.findByCondition(map)
        if(findByCondition.size > 0){
            return findByCondition[0]
        }
        return null
    }

    /**
     * 设置默认地址
     */
    fun setDefault(id: Long): R<*> {
        val map = mutableMapOf<String,Any?>()
        map.put("id",id)
        map.put("del",BoolState.NO)
        val address = findByCondition(map)
        if(address == null){
            LOG.info("当前地址不存在")
            return R.ER("当前地址不存在")
        }
        if(BoolState.YES.equals(address.def_)){
            return R.OK("设置成功")
        }
        return doSetDefaultDb(address)
    }


    /**
     * 默认地址，更新 数据库
     */
    @Transactional(rollbackFor = arrayOf(Exception::class))
    open fun doSetDefaultDb(address:Address):R<*>{

        addressDao.clearDefault(address.userid!!)

        val upOne = Address()
        upOne.id = address.id
        upOne.def_ = BoolState.YES
        val updateOne = addressDao.updateSelective(upOne)
        if(updateOne <= 0){
            return R.ER("更新失败")
        }
        return R.OK("更新成功",address.id)

    }

    /**
     * 新增地址
     */
    fun saveAddress(address: Address): R<*> {
        address.userid
        return R.OK()
    }


}